Imshow in R
How to display image data in Python with R.
New to Plotly?
Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.
This tutorial shows how to display and explore image data. If you would like instead a logo or static image, use layout.Image as explained here.
Display RGB Image Data with Image Trace
Note that Image trace only accepts multichannel images. For single images, use Heatmap. Image trace is different from the layout.Image class, which can be used for adding background images or logos to figures.
library(plotly)
img_rgb = list(list(c(255, 0, 0),c(0, 255, 0),c(0, 0, 255)),
list(c(0,255, 0),c(0, 0, 255),c(255, 0, 0)))
fig <- plot_ly(type="image", z=img_rgb)
fig
Read image arrays from image files
In order to create a numerical array to be passed to Image trace, you can use a third-party library like EBImage to open an image from a URL.
library(plotly)
library(EBImage)
img = readImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
fig <- plot_ly(type="image", z=img*255)
fig
Define the data range covered by the color range with zmin and zmax
The data range and color range are mapped together using the parameters zmin and zmax, which correspond respectively to the data values mapped to black [0, 0, 0] and white [255, 255, 255].
The default value of zmin and zmax depends on the colormodal value. In this example colormodel is "rgb"(by default), so the default value of zmin is [0, 0, 0] and zmax is [250, 250, 250].
library(plotly)
library(EBImage)
img = readImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
# Stretch the contrast of the red channel only, resulting in a more red image
fig <- plot_ly(type="image", z=img*250,
zmin=c(10, 0, 0), zmax=c(200, 250, 250))
fig
Set Ticks and Margins
library(plotly)
library(EBImage)
img = readImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
fig <- plot_ly(type="image", z=img*250)
fig <- fig %>% layout(margin=list(l=10, r=10, b=0, t=0),
xaxis=list(showticklabels=FALSE, ticks=""),
yaxis=list(showticklabels=FALSE, ticks=""))
fig
Combine image charts and other traces
library(plotly)
library(EBImage)
img = readImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
fig <- plot_ly(type="image", z=img*250)
fig <- fig %>% add_trace(
type='bar', y=c(50, 60), x=c(40, 50),
marker=list(color='pink', size=10))
fig
Reference
See https://plot.ly/r/reference/#image for more information and chart attribute options!

